package com.linewow.xhyy.nihaonew.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.activity.TopicDetailActivity;
import com.linewow.xhyy.nihaonew.adapter.ImagesInfoAdapterLoad;
import com.linewow.xhyy.nihaonew.application.NiHaoApp;
import com.linewow.xhyy.nihaonew.base.BaseEntity;
import com.linewow.xhyy.nihaonew.base.BaseFragment;
import com.linewow.xhyy.nihaonew.base.BaseInfo;
import com.linewow.xhyy.nihaonew.entity.UserMineInfo;
import com.linewow.xhyy.nihaonew.entity.image.ImagesInfo;
import com.linewow.xhyy.nihaonew.entity.user.Uinfo;
import com.linewow.xhyy.nihaonew.entity.user.UserInfo;
import com.linewow.xhyy.nihaonew.net.api.NiHaoOkgo;
import com.linewow.xhyy.nihaonew.view.ItemOffsetDecoration;
import com.peekandpop.shalskar.peekandpop.PeekAndPop;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
/**
 * Created by LXR on 2016/10/10.
 * 用的baseinfo 实体类少一个属性
 */
public class MinePhotoFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener {
    @Bind(R.id.mine_photo_recycler)
    RecyclerView minePhotoRecycler;
    private String TAG = "MinePhotoFragment";
    private ImagesInfoAdapterLoad adapter;
    private Type imagesInfoType;
    private Gson gson;
    private Uinfo uinfo;
    private int page=1;
    private boolean userFlag;
    private PeekAndPop peekAndPop;

    @Override
    public void initList() {
        super.initList();
         peekAndPop=new PeekAndPop.Builder(MinePhotoFragment.this.getActivity())
                .blurBackground(false)
                .peekLayout(R.layout.peek_view)
                .parentViewGroupToDisallowTouchEvents(minePhotoRecycler)
                .build();
    }

    @Override
    public View initView() {
        View view = View.inflate(getActivity(), R.layout.fragment_mine_photo, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void initData() {
        super.initData();
        GridLayoutManager manager=new GridLayoutManager(getActivity(),3);
        manager.setOrientation(GridLayoutManager.VERTICAL);
        minePhotoRecycler.setLayoutManager(manager);
        minePhotoRecycler.setItemAnimator(new DefaultItemAnimator());
        minePhotoRecycler.addItemDecoration(new ItemOffsetDecoration(2));
        imagesInfoType=new TypeToken<BaseInfo<ImagesInfo>>(){}.getType();
        gson=new Gson();
        Bundle bundle=getArguments();
        if(bundle==null){
            userFlag=false;
            refreshData();
        }else{
            userFlag=true;
            uinfo=bundle.getParcelable("info");
            refreshUserData();
        }



        minePhotoRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                ImagesInfo info= (ImagesInfo) baseQuickAdapter.getData().get(i);
                startDetailActivity(info.tid);
            }
        });
    }



    private void requestUserInfo() {
        NiHaoOkgo.userPhoto(uinfo.uid,page)
                .map(new Func1<BaseEntity<UserMineInfo<UserInfo,List<ImagesInfo>>>,List<ImagesInfo> >() {
                    @Override
                    public List<ImagesInfo> call(BaseEntity<UserMineInfo<UserInfo, List<ImagesInfo>>> userMineInfoBaseEntity) {
                        List<ImagesInfo>imagesInfos=new ArrayList<ImagesInfo>();
                        UserMineInfo<UserInfo,List<ImagesInfo>>userMineInfo=userMineInfoBaseEntity.data;
                        List<List<ImagesInfo>>infoss=userMineInfo.data;
                        for(int i=0;i<infoss.size();i++){
                            imagesInfos.addAll(infoss.get(i));
                        }
                        return imagesInfos;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<ImagesInfo>>() {
                    @Override
                    public void call(List<ImagesInfo> imagesInfos) {
                        if(adapter==null){
                            Log.e(TAG,"刷新");
                            adapter=new ImagesInfoAdapterLoad(imagesInfos,peekAndPop);
                            adapter.isFirstOnly(false);
                            minePhotoRecycler.setAdapter(adapter);
                            adapter.setOnLoadMoreListener(MinePhotoFragment.this);
                        }else{
                            Log.e(TAG,"加载");
                            adapter.addData(imagesInfos);
                            if(imagesInfos.size()<12){
                                adapter.loadComplete();
                            }
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(TAG, "错误信息" + throwable.getMessage());
                        showToast(getString(R.string.message_no_internet));
                    }
                });
    }



    private void requestInfo() {
        OkHttpUtils.get().url("https://m.en1on1.com/api/api1.5/homepage.php?ac=loadphotos&page="+page+"&token=" + NiHaoApp.token)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e(TAG, "接受到的" + response);
                        BaseInfo<ImagesInfo>baseInfo=gson.fromJson(response,imagesInfoType);
                        Log.e(TAG,"大小"+baseInfo.data.size());
                        List<ImagesInfo> imagesInfos = baseInfo.data;
                        if(adapter==null){


                            adapter=new ImagesInfoAdapterLoad(imagesInfos,peekAndPop);
                            adapter.isFirstOnly(false);
                            minePhotoRecycler.setAdapter(adapter);
                            adapter.setOnLoadMoreListener(MinePhotoFragment.this);
                        }else{
                            if(page!=1){
                                adapter.addData(imagesInfos);
                                if(imagesInfos.size()<12){
                                    adapter.loadComplete();
                                }
                            }else{//刷新界面的时候
                                adapter.setNewData(imagesInfos);
                                adapter.openLoadMore(12);
                            }

                        }
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onLoadMoreRequested() {
        if(userFlag){
            loadUserData();
        }else{
            loadData();
        }
    }

    private void loadData() {
        page++;
        requestInfo();
    }
    public void refreshData() {
        page=1;
        requestInfo();
    }


    private void refreshUserData() {
        page=1;
        requestUserInfo();
    }
    private void loadUserData() {
        page++;
        requestUserInfo();
    }

    public void startDetailActivity(String tid){
        Intent intent=new Intent(MinePhotoFragment.this.getActivity(), TopicDetailActivity.class);
        intent.putExtra("msg",tid);
        startActivity(intent);
    }
}
